package com.cupk.service.impl;

import com.cupk.mapper.UserMapper;
import com.cupk.pojo.User;
import com.cupk.service.UserService;
import com.cupk.utils.JwtUtil;
import com.cupk.utils.Md5Util;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
@Primary
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Resource
    public JavaMailSender javaMailSender;
    @Resource
    private TemplateEngine templateEngine;
    @Value("${spring.mail.username}")
    private String sendUserMailName;


    @Override
    public void sendEmail(String username, String email, String code) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setSubject("【石油学院双创管理平台】教师激活绑定邮箱验证码");
            helper.setFrom(sendUserMailName);
            helper.setTo(email);
            helper.setSentDate(new Date());
            //这里进入的是Template的Context
            Context context = new Context();
            //设置模板中的变量
            context.setVariable("username", username);
            context.setVariable("code", code);
            //第一个参数作为模板的，名称
            String process = templateEngine.process("email.html", context);
            //第二个参数true表示这是html文本
            helper.setText(process, true);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException ex) {
            throw new RuntimeException("发送失败！");
        }
    }

    @Override
    public String generateCode() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder verifyCode = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < 6; i++) {
            verifyCode.append(chars.charAt(random.nextInt(chars.length())));
        }

        return verifyCode.toString();
    }

    @Override
    public User getUserByAccount(String account) {
        return userMapper.getUserByAccount(account);
    }

    @Override
    public void register(User user) {
        System.out.println(user.getPassword());
        user.setPassword(Md5Util.getMD5String(user.getPassword()));
        userMapper.register(user);
    }

    @Override
    public void updateEmail(String userId, String email) {
        userMapper.updateEmailById(userId, email);
    }

    @Override
    public void updatePassword(String userId, String newPassword) {
        String password = Md5Util.getMD5String(newPassword);
        userMapper.updatePasswordById(userId,password);
    }

    @Override
    public User getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }

    @Override
    public User getUserByName(String name) {
        return userMapper.getUserByName(name);
    }

    public String generateToken(User user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("name", user.getName());
        claims.put("role", user.getRole());
        claims.put("account", user.getAccount());
        String token = JwtUtil.genToken(claims);
        return token;
    }

}
